<?php
/**
  * Use：
  * Author：kan.yang@starcor.cn
  * DateTime：18-2-1 下午2:51
  * Description：
*/
set_time_limit(0);error_reporting(0);
header('Content-Type:text/xml; charset=utf-8');
include_once dirname(dirname(dirname(dirname(__FILE__))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
//加载 xml转为数组的np库
\ns_core\m_load::load_np("np_xml_to_array.class.php");
\ns_core\m_load::load_np("np_xml2array.class.php");
\ns_core\m_load::load_old("nn_logic/queue/queue_redis.class.php");
//加载 xml转为数组的np库
\ns_core\m_load::load_old("nn_class/ftp/ftp.class.php");
//调用memcache
\ns_core\m_load::load_old("nn_logic/cache/view_cache.class.php");

class script_asset_data
{
    private $obj_dc = null;

    private $str_ftp_url  ='ftp://yangkan:yk@127.0.0.1:21';

    private $arr_sp_ids = array('coship','starcor_mp3');
    private $arr_cp_ids = array('xiaole_mp3','xiaole_encode','fuse_xiaole');

    private $arr_repeat_vod_list = array();
    private $arr_repeat_index_list = array();
    private $arr_repeat_media_list = array();

    //private

    public function __construct()
    {
        $this->obj_dc = m_config::get_dc();
    }

    public function init()
    {
        //$this->primary_file_errors();

        //参数1：CPID；参数2：媒资类型1,2,3；参数3：全部跑
        $this->import_asset_center($_SERVER['argv'][1],$_SERVER['argv'][2],$_SERVER['argv'][3]);
    }

    private function import_asset_center($str_scp_ids = '',$str_type = '1,2,3',$int_all = 0)
    {
        $arr_type = empty($str_type) ? array(1,2,3) : explode(',',$str_type);

        $arr_scp_ids = empty($str_scp_ids) ? $this->arr_cp_ids : explode(',',$str_scp_ids);

        include_once dirname(dirname(dirname(dirname(__FILE__)))) . "/ns_timer/import/import_message.timer.php";
        include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/mgtv_v2/mgtv_init.php';
        include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/nn_logic/message/message_group.class.php';
        include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/nn_logic/message/nl_message.class.php';
        include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/nn_logic/message/message_group_list.class.php';

        foreach($arr_scp_ids as $k => $id)
        {
            foreach($arr_type as $i)
            {
                //消息 => 中心注入
                $this->import_asset_center_base($id,array($i),$int_all);
                //中心注入 => 中心同步
//                $this->center_import_to_toggle($id,array($i));

                usleep(100000);
            }
        }
    }

    private function import_asset_center_base($str_cp_id,$arr_video_type = array(1,2,3),$int_all = 0)
    {
        $str_sql = "SELECT m.* FROM
                      nns_mgtvbk_message m
                      LEFT JOIN nns_mgtvbk_import_op o
                        ON (
                          o.`nns_message_id` = m.`nns_message_id`
                          AND o.`nns_cp_id` = '{$str_cp_id}'
                        )
                    WHERE m.`nns_cp_id` = '{$str_cp_id}'
                      AND m.nns_type IN (" . implode(',',$arr_video_type) . ")
                      AND o.`nns_message_id` IS NULL";

        $str_sql = "SELECT m.* FROM
                      nns_mgtvbk_message m
                    WHERE m.`nns_cp_id` = '{$str_cp_id}'
                      AND m.nns_type IN (" . implode(',',$arr_video_type) . ")
                      AND m.`nns_message_id` NOT IN
                      (SELECT
                        o.nns_message_id
                      FROM
                        nns_mgtvbk_import_op o
                      WHERE o.`nns_cp_id` = '{$str_cp_id}')";

        $str_sql = "SELECT m.* FROM
                      nns_mgtvbk_message m
                    WHERE m.`nns_cp_id` = '{$str_cp_id}'
                      AND m.nns_type IN (" . implode(',',$arr_video_type) . ")
                      AND nns_create_time >= '2018-04-08 14:44:00'
                      AND m.`nns_message_state` = 4";

        if(isset($int_all) && $int_all == 1)
        {
            //$str_sql = "SELECT m.* FROM nns_mgtvbk_message m WHERE m.`nns_cp_id` = '{$str_cp_id}' AND m.nns_type IN (" . implode(',',$arr_video_type) . ")";
        }

        $arr_list = nl_query_by_db($str_sql,$this->obj_dc->db());
        if(is_array($arr_list) && !empty($arr_list))
        {
            //注入
            $timer = new import_message_timer(m_config::return_child_path(dirname(dirname(dirname(dirname(__FILE__)))) . "/ns_timer/import/import_message.timer.php",'timer'),$str_cp_id);
            $timer->run(array('ret' => 0, 'data_info' => $arr_list));
        }
    }

    private function center_import_to_toggle($str_cp_id,$arr_video_type = array(1,2,3))
    {
        $str_video_type = '';
        if(!empty($arr_video_type))
        {
            if(in_array(1,$arr_video_type))
            {
                $str_video_type .= 'video,';
            }
            if(in_array(2,$arr_video_type))
            {
                $str_video_type .= 'index,';
            }
            if(in_array(3,$arr_video_type))
            {
                $str_video_type .= 'media,';
            }
            $str_video_type = rtrim($str_video_type,',');
        }
        else
        {
            $str_video_type = 'video,index,media';
        }
        $str_video_type = implode("','",explode("','",$str_video_type));

        //SQL
        $str_sql = "SELECT o.`nns_id`, s.`nns_id` nns_sp_id FROM
                      nns_mgtvbk_import_op o
                      INNER JOIN `nns_mgtvbk_sp` s
                        ON (
                          LOCATE(
                            CONCAT(',', o.`nns_cp_id`, ','),
                            s.`nns_bind_cp`
                          ) > 0
                        )
                    WHERE o.`nns_cp_id` = '{$str_cp_id}'
                      AND o.`nns_video_type` IN ('" . $str_video_type . "')
                      AND o.`nns_message_id` NOT IN
                      (SELECT
                        nns_message_id
                      FROM
                        nns_mgtvbk_op_queue q
                      WHERE q.`nns_cp_id` = '{$str_cp_id}'
                        AND q.`nns_type` IN ('" . $str_video_type . "'))";

        $arr_list = nl_query_by_db($str_sql,$this->obj_dc->db());
        if(is_array($arr_list) && !empty($arr_list))
        {
            //同步
            $queue_task_model = new queue_task_model();
            foreach ($arr_list as $val)
            {
                $queue_task_model->add_task_to_queue($val['nns_sp_id'], $val['nns_id']);
                echo $val['nns_sp_id'] . '=>' . $val['nns_id'] . ',';
                usleep(50000);
            }
            echo '中心注入 => 中心同步：' . count($arr_list);
        }
        else
        {
           if(is_bool($arr_list) && $arr_list === false)
           {
                echo 'sql语句执行失败：' . $str_sql . '\n\r\t';
           }
            else
            {
                echo '查询无任何数据\n\r\t';
            }
        }
    }

    //扫描原始文件，提出错误媒资
    private function primary_file_errors()
    {
        foreach($this->arr_cp_ids as $k =>$id)
        {
            $str_cache_key = nl_view_cache::gkey(
                'message_ftp_import_file_url_' . $id,
                array('message_ftp_import_file_url_' . $id, __FILE__)
            );
            $ftp_url = $this->str_ftp_url . '/' . $id;

            //nl_queue_redis::delete_key(m_config::get_redis_dc(), $str_cache_key);

            $result_redis = nl_queue_redis::get_list(m_config::get_redis_dc(), $str_cache_key);

            //$this->ftp_get_files($ftp_url,$str_cache_key);

            $arr_file_list = $result_redis['data_info'];

            $this->check_data($arr_file_list,$id);
        }
    }

    private function check_data($arr_file_list,$str_cp_id)
    {
        foreach($arr_file_list as $values)
        {
            //数据有效性
            if(!m_config::is_json($values)) continue;
            $values = json_decode($values,true);
            //遍历入库
            foreach ($values as $file_val)
            {
                //原始数据存储的字段
                $result_content = m_config::get_curl_content($file_val);
                if($result_content['ret'] !=0)
                {
                    continue;
                }
                else if(!isset($result_content['data_info']) || strlen($result_content['data_info']) <1)
                {
                    m_config::return_data(1,"获取CP[".$str_cp_id."]ftp文件内容为空，地址[{$file_val}]");
                    continue;
                }

                $str_content = m_config::trim_xml_header($result_content['data_info']);
                if(!m_config::is_xml($str_content))
                {
                    m_config::return_data(1,"消息xml内容非xml结构");
                    continue;
                }
                //解析下载的XML
                $dom = new DOMDocument('1.0', 'utf-8');
                $dom->loadXML($str_content);
                $xml = $dom->saveXML();
                $xml_arr = np_xml2array::getArrayData($xml);
                if ($xml_arr["ret"] == 0)
                {
                    m_config::return_data(1,"消息xml解析失败");
                    continue;
                }
                $Objects = null;
                foreach ($xml_arr['data']['children'] as $v)
                {
                    if (empty($Objects) && $v['name'] == 'Objects')
                    {
                        $Objects = $v['children'];
                    }
                    else if (empty($this->arr_map) && $v['name'] == 'Mappings')
                    {
                        $this->arr_map = $v['children'];
                    }
                }
                $flag = true;
                if (!empty($Objects) && is_array($Objects))
                {
                    foreach ($Objects as $obj)
                    {
                        if ($obj['attributes']['ElementType'] == 'Series')
                        {
                            if(in_array($obj['attributes']['ID'],$this->arr_repeat_vod_list))
                            {
                                $flag = false;
                                break;
                            }
                        }
                        else if ($obj['attributes']['ElementType'] == 'Program')
                        {
                            if(in_array($obj['attributes']['ID'],$this->arr_repeat_index_list))
                            {
                                $flag = false;
                                break;
                            }
                        }
                        else if ($obj['attributes']['ElementType'] == 'Movie')
                        {
                            if(in_array($obj['attributes']['ID'],$this->arr_repeat_media_list))
                            {
                                $flag = false;
                                break;
                            }

                            $temp_key_value_arr = $this->make_key_value_arr($obj);
                            $str_FileURL = isset($temp_key_value_arr['key_val_list']['FileURL']) ? trim(ltrim(ltrim($temp_key_value_arr['key_val_list']['FileURL'],'/'),'\\')) : '';
                            if(strlen($str_FileURL) <= 0)
                            {
                                $flag = false;
                                break;
                            }
                            $result = $this->check_file_exsist(trim(trim(trim($this->str_ftp_url,'/'),'\\')).'/'.$str_FileURL);
                            if($result['ret'] !=0)
                            {
                                $flag = false;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    $flag = false;
                }
                if(!$flag)
                {
                    continue;
                }
            }
        }
    }

    private function make_key_value_arr($xml_obj_arr)
    {
        $key_val_array = null;
        if (isset($xml_obj_arr['attributes']) && is_array($xml_obj_arr['attributes']) && !empty($xml_obj_arr['attributes']))
        {
            foreach ($xml_obj_arr['attributes'] as $attr_key => $attr_val)
            {
                $key_val_array[$attr_key] = $attr_val;
            }
            if(!isset($key_val_array['ContentID']) || strlen($key_val_array['ContentID'])<1)
            {
                $key_val_array['ContentID'] = isset($xml_obj_arr['attributes']['ID']) ? $xml_obj_arr['attributes']['ID'] : '';
            }
            unset($xml_obj_arr['attributes']);
        }
        if (isset($xml_obj_arr['children']) && is_array($xml_obj_arr['children']) && !empty($xml_obj_arr['children']))
        {
            foreach ($xml_obj_arr['children'] as $key_list)
            {
                if (isset($key_list['attributes']['Name']) && strlen($key_list['attributes']['Name']) > 0)
                {
                    $key_val_array['key_val_list'][$key_list['attributes']['Name']] = (isset($key_list['content']) && strlen($key_list['content']) > 0) ? trim($key_list['content']) : '';
                }
            }
            unset($xml_obj_arr['children']);
        }
        return $key_val_array;
    }

    private function check_file_exsist($ftp_url)
    {
        $ftp_url = trim($ftp_url,'/');
        $arr_ftp_config = parse_url($ftp_url);
        $host_ftp = (isset($arr_ftp_config["host"]) && strlen($arr_ftp_config["host"]) > 0) ? $arr_ftp_config["host"] : '';
        $user_ftp = (isset($arr_ftp_config["user"]) && strlen($arr_ftp_config["user"]) > 0) ? $arr_ftp_config["user"] : '';
        $pass_ftp = (isset($arr_ftp_config["pass"]) && strlen($arr_ftp_config["pass"]) > 0) ? $arr_ftp_config["pass"] : '';
        $path_ftp = (isset($arr_ftp_config["path"]) && strlen($arr_ftp_config["path"]) > 0) ? $arr_ftp_config["path"] : '';
        $port_ftp = (isset($arr_ftp_config["port"]) && strlen($arr_ftp_config["port"]) > 0) ? $arr_ftp_config["port"] : 21;
        $obj_ftp = new nl_ftp($host_ftp, $user_ftp, $pass_ftp,$port_ftp);
        $result = $obj_ftp->check_file_exsist($path_ftp);
        unset($obj_ftp);
        return $result;
    }

    //拉取FTP媒资
    private function ftp_get_files($ftp_url,$str_cache_key,$file_ex = 'xml',$message_ftp_import_num = 1000)
    {
        $message_ftp_import_num = (int)$message_ftp_import_num>0 ? (int)$message_ftp_import_num : 100;
        $arr_files = null;
        $ftp_url = trim($ftp_url,'/');
        $arr_ftp_config = parse_url($ftp_url);
        $host_ftp = (isset($arr_ftp_config["host"]) && strlen($arr_ftp_config["host"]) > 0) ? $arr_ftp_config["host"] : '';
        $user_ftp = (isset($arr_ftp_config["user"]) && strlen($arr_ftp_config["user"]) > 0) ? $arr_ftp_config["user"] : '';
        $pass_ftp = (isset($arr_ftp_config["pass"]) && strlen($arr_ftp_config["pass"]) > 0) ? $arr_ftp_config["pass"] : '';
        $path_ftp = (isset($arr_ftp_config["path"]) && strlen($arr_ftp_config["path"]) > 0) ? $arr_ftp_config["path"] : '';
        $port_ftp = (isset($arr_ftp_config["port"]) && strlen($arr_ftp_config["port"]) > 0) ? $arr_ftp_config["port"] : 21;
        $obj_ftp = new nl_ftp($host_ftp, $user_ftp, $pass_ftp,$port_ftp);
        $result_conn = $obj_ftp->base_opration_ftp();
        if(strlen($path_ftp) >0)
        {
            $ftp_url=trim(substr($ftp_url,0, (-strlen($path_ftp))),'/');
        }
        if(!$result_conn)
        {
            return m_config::return_data(1,"ftp链接失败,原因：".var_export($obj_ftp->make_error_data(),true));
        }
        $result = $obj_ftp->ftp_recursive_file_listing($path_ftp.'/',$file_ex);
        if(empty($result) || !is_array($result))
        {
            return m_config::return_data(1,"未查询到任何文件信息,相对路径[{$ftp_url}]");
        }
        foreach ($result as $key => $val)
        {
            foreach ($val as $file_val)
            {
                $arr_files[] = $ftp_url .'/'.trim($key.'/'.trim($file_val,'/'),'/');
            }
        }
        if(is_array($arr_files) && !empty($arr_files))
        {
            $arr_files = array_chunk($arr_files,$message_ftp_import_num);
            foreach ($arr_files as $val_file)
            {
                if(empty($val_file) || !is_array($val_file))
                {
                    continue;
                }
                $val_file = json_encode($val_file);
                $result = nl_queue_redis::push(m_config::get_redis_dc(), $str_cache_key, $val_file);
                if($result['ret'] != 0)
                {
                    return $result;
                }
            }
        }
        return m_config::return_data(0,"OK,ftp文件相对路径[{$ftp_url}]");
    }

}

$obj_script_asset_data = new script_asset_data();
$obj_script_asset_data->init();
